import hmac
import base64
from hashlib import sha256
import urllib
import json
import requests
import redis
import time
import threading
from django.shortcuts import redirect
from user.models import User


# 钉钉三方登录
def ding_back(request):
    appid = 'dingoas3kikmnruiywyjbq'
    redirect_uri = 'http://127.0.0.1:8000/p8/ding_back/'
    # return redirect(
    #     'https://oapi.dingtalk.com/connect/qrconnect?appid=' + appid + '&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=' + redirect_uri)
    # 构造钉钉回调方法
    # 获取code
    code = request.GET.get("code")

    t = time.time()
    # 时间戳
    timestamp = str((int(round(t * 1000))))
    appSecret = '5O9I7G3HMr4polx2C670xiM1N9_9_Xpe0zl2Ha0xFLBV8GGU6MJWs0aqG-5UZDYQ'
    # 构造签名
    signature = base64.b64encode(
        hmac.new(appSecret.encode('utf-8'), timestamp.encode('utf-8'), digestmod=sha256).digest())
    # 请求接口，换取钉钉用户名
    payload = {'tmp_auth_code': code}
    headers = {'Content-Type': 'application/json'}
    res = requests.post('https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature=' + urllib.parse.quote(
        signature.decode("utf-8")) + "&timestamp=" + timestamp + "&accessKey=dingoas3kikmnruiywyjbq",
                        data=json.dumps(payload), headers=headers)

    re_dict = json.loads(res.text)
    # 判断是否为第一次登录
    user = User.objects.filter(username=str('dingding_' + re_dict['user_info']['nick'])).first()

    sina_id = ''
    user_id = ''

    if user:
        # 代表曾经用过钉钉登录
        sina_id = user.username
        user_id = user.id
    else:
        # 代表首次登录，入库
        user = User(username=str("dingding_" + re_dict['user_info']['nick']), password='')
        # 保存入库
        user.save()
        sina_id = str(re_dict['user_info']['nick'])
        print(sina_id)
        # 查询用户id
        user = User.objects.filter(username=str("dingding_" + re_dict['user_info']['nick'])).first()
        user_id = user.id

    # 进行跳转
    return redirect("http://127.0.0.1:8080/myback?sina_id=" + str(sina_id) + "&uid=" + str(user_id))


# gitee三方登录
def gitee_back(request):
    code = request.GET.get("code")
    x = requests.post(
        "https://gitee.com/oauth/token?grant_type=authorization_code&code=%s&client_id=91081b1ce037b7f354a099b2b9619349ba782624a87bcc6f21d03b7cdf7d405a&redirect_uri=http://127.0.0.1:8000/p8/gitee_back/&client_secret=3662c2013dc85d216ad21242be4abcada1cc71877095c0c40bd3d6d1f0380ea3" % code)
    print(x.text)

    r = requests.get("https://gitee.com/api/v5/user?access_token=" + x.json()['access_token'])

    print(r.text)
    user = User.objects.filter(username=str('gitee_' + r.json()['name'])).first()

    sina_id = ''
    user_id = ''

    if user:
        # 代表曾经用过钉钉登录
        sina_id = user.username
        user_id = user.id
    else:
        # 代表首次登录，入库
        user = User(username=str('gitee_' + r.json()['name']), password='')
        # 保存入库
        user.save()
        sina_id = str(r.json()['name'])
        print(sina_id)
        # 查询用户id
        user = User.objects.filter(username=str("gitee_" + r.json()['name'])).first()
        user_id = user.id

    # 进行跳转
    return redirect("http://127.0.0.1:8080/myback?sina_id=" + str(sina_id) + "&uid=" + str(user_id))
